<?php
namespace app\controller;

use think\facade\View;
use app\model\ADdnsIpRuleServerApi;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
 
 class Index
 {
     public function index()
     {
         View::assign('name', '欢迎使用 ThinkPHP 6！');
         return View::fetch('index');
     }

     public function api()
     { 
        return View::fetch('home');
     }

     public function home()
     { 
        return View::fetch('home');
     }

     public function getlogin() {  
        $token = bin2hex(random_bytes(32));  
        $postData = json_decode(file_get_contents('php://input'), true); 
        if(trim($postData['username']) == 'user123' && trim($postData['password']) == 'admin123'){
            $this->ajaxReturn(['status' => 'success', 'username' =>'user123','password' => 'admin123'], 'json'); 
        }else{
            $this->ajaxReturn(['status' => 'error', 'data' =>[],'token' => ''], 'json'); 
        } 
    }
 
     public function getAllIps()
     {
         $batchSize = 1000;
 
         // 使用模型类进行数据查询
         $existingIps = ADdnsIpRuleServerApi::field('server_addr')
             ->limit($batchSize)
             ->select()
             ->toArray();
 
         // 获取数据总量
         $total = ADdnsIpRuleServerApi::count();
 
         // 分批次查询
         $totalBatches = ceil($total / $batchSize);
         for ($i = 0; $i < $totalBatches; $i++) {
             $offset = $i * $batchSize;
             $batchIps = ADdnsIpRuleServerApi::field('server_addr')
                 ->limit($offset, $batchSize)
                 ->select()
                 ->toArray();
         }
     }
     public function getIpData()
     { 
         
         // 使用模型获取 IP 数据
         $ipData = ADdnsIpRuleServerApi::order('is_main_addr', 'desc')
             ->order('update_time', 'desc')
             ->field('id, server_addr, is_main_addr, server_id, create_time, update_time, rent_time, status')
             ->select()
             ->toArray();
 
          
         // 统计每个 `server_id` 对应的 IP 数量
         $ruleIpCount = [];
         foreach ($ipData as $item) {
             $server_id = '';
             if (!isset($ruleIpCount[$server_id])) {
                 $ruleIpCount[$server_id] = 0;
             }
             $ruleIpCount[$server_id]++;
         }
 
         // 初始化存储分组的 IP 数据
         $groupedData = [];
         $ruleServerCount = [];
 
         // 按房间号（如 303、302）进行分组
         foreach ($ipData as &$item) {
             $room = $server_id; // 假设 `server_id` 是房间号
             $item['rule_name'] = $room;
             $groupId = $item['server_id'];
 
             // 初始化每个房间的数据结构
             if (!isset($groupedData[$room])) {
                 $groupedData[$room] = [];
             }
 
             if (!isset($groupedData[$room][$groupId])) {
                 // 初始化该组的时间和 IP 列表
                 $groupedData[$room][$groupId] = [
                     'ruleName' => $room,
                     'group' => $groupId,
                     'time' => $item['rent_time'],
                     'ips' => [],
                     'count' => 0,
                 ];
             }
 
             // 将 IP 和其主 IP 标记添加到对应的组
             $groupedData[$room][$groupId]['ips'][] = [
                 'ip' => $item['server_addr'],
                 'is_main_addr' => $item['is_main_addr'],
                 'status' => $item['status']
             ];
             $groupedData[$room][$groupId]['count'] = count($groupedData[$room][$groupId]['ips']);
             $ruleServerCount[$room] = count($groupedData[$room]);
         }
 
         // 按数量排序
         arsort($ruleIpCount);
         arsort($ruleServerCount);
 
         // 检查是否需要导出数据
         $export = isset($_REQUEST['export']) ? intval($_REQUEST['export']) : 0; 
          
         if ($export) {
             $this->exportDataToExcelOne($groupedData);
         } else {
             return json([
                 'status' => 'success',
                 'data' => $groupedData,
                 'allData' => $ipData,
                 'ruleIpCount' => $ruleIpCount,
                 'ruleServerCount' => $ruleServerCount,
             ]);
         }
     }

     public function dealWords($word){
        if(empty($word)){
            return [];
        }
        $dealData = str_replace(
            [PHP_EOL, "\n", "\r\n", "\r", ',', '，', ';', '；',' '],
            "\n",
            trim($word)
        ); 
        //dd($dealData);
        $dealData = explode("\n", $dealData);
        foreach ($dealData as $k => $v) {
            $dealData[$k] = trim($v);
        }
        $dealData = array_unique(array_filter($dealData));
        return $dealData; 
    } 
 
     public function ip_manage_add()
     {  
         $postData = json_decode(file_get_contents('php://input'), true);
         $serverAddr = !empty($postData['serverAddr']) ? $postData['serverAddr'] : ''; 
         $serverAddrOne = !empty($postData['serverAddrOne']) ? trim($postData['serverAddrOne']) : '';  
 
         // 获取最大 server_id
         $max_id = ADdnsIpRuleServerApi::max('server_id');
         $serverId = $max_id + 1;
 
         $Server_addr = $this->dealWords($serverAddr);
         $Server_addr['-1'] = $serverAddrOne;  
 
         if (empty($Server_addr)) {
             return $this->ajaxReturn([
                 'status' => 'error', 
                 'message' => '上传IP不能为空!',
                 'notIp' => [],
                 'duplicateIp' => []
             ], 'json'); 
         }
 
         $Server_addr = array_filter($Server_addr); 
 
         // 正则校验 IP
         $ipv4Pattern = '/^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/';
         $ipv6Pattern = '/^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/';
 
         $notIp = [];
         $duplicateIp = [];
         $insertData = [];
         $time = time();
 
         // 获取已存在的 IP
         $existingIps = ADdnsIpRuleServerApi::column('server_addr');
         $existingIps = array_flip($existingIps);
 
         foreach ($Server_addr as $k => $ip) {
             if (!preg_match($ipv4Pattern, $ip) && !preg_match($ipv6Pattern, $ip)) {
                 $notIp[] = $ip;
                 break;
             }
 
             if (isset($existingIps[$ip])) {
                 $duplicateIp[] = $ip;
                 break;
             }
 
             $isMain = $k === -1 ? 2 : 0;
 
             $insertData[] = [
                 'server_id' => $serverId,
                 'is_main_addr' => $isMain,
                 'server_addr' => $ip,
                 'create_time' => $time,
                 'update_time' => $time,
             ];
         }
 
         if (count($notIp) > 0 || count($duplicateIp) > 0) {
             return $this->ajaxReturn([
                 'status' => 'error',
                 'message' => '添加 IP 地址失败',
                 'notIp' => $notIp,
                 'duplicateIp' => $duplicateIp
             ], 'json');
         }
 
         if (!empty($insertData)) {
             $result = ADdnsIpRuleServerApi::insertAll($insertData);
 
             if ($result) {
                 return $this->ajaxReturn([
                     'status' => 'success',
                     'message' => 'IP 地址添加成功',
                     'notIp' => $notIp,
                     'duplicateIp' => $duplicateIp
                 ], 'json');
             }
         }
     }

     public function addIp()
{
    
    $tableName = 'AD_dns_ipRuleServer_api';
     
    $postData = json_decode(file_get_contents('php://input'), true);  

    if (empty($postData['server_addr'])) {
        $this->ajaxReturn(['status' => 'error', 'message' => 'ip地址不能为空!'], 'json');
        return;
    }
    $server_addr = trim($postData['server_addr']);
    $ipv4Pattern = '/^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/';
    $ipv6Pattern = '/^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/';

    if (!preg_match($ipv4Pattern, $server_addr) && !preg_match($ipv6Pattern, $server_addr)) {
        $this->ajaxReturn(['status' => 'error', 'message' => 'IP地址不符合规范!'], 'json');
    } 

    $exist = ADdnsIpRuleServerApi::where(['server_addr' => $server_addr])->find();
    if($exist){
        $this->ajaxReturn(['status' => 'error', 'message' => '数据库已存在该IP!'], 'json');
    }

    $is_main_addr = !empty($postData['is_main_addr']) ? $postData['is_main_addr'] : 0;
    $server_id = $postData['group_id'];
     
    
    

    if($is_main_addr){ 
        ADdnsIpRuleServerApi::where(['server_id' => $server_id])
            ->where(['is_main_addr' => $is_main_addr])
            ->update(['is_main_addr' => 0]);
    } 

    $insert = [ 
        'server_id' => $server_id,
        'is_main_addr' => $is_main_addr,
        'server_addr' => $server_addr,
        'create_time' => time(), 
        'update_time' => time(), 
    ];

    $result = ADdnsIpRuleServerApi::insert($insert);

    if ($result) {
        return $this->ajaxReturn(['status' => 'success', 'msg' => 'IP 地址添加成功！'], 'json'); 
    }else{
        return $this->ajaxReturn(['status' => 'error', 'msg' => 'IP 地址添加失败！'], 'json'); 
    }  
}

     protected function ajaxReturn($data, $type = '', $json_option = 0)
     {
         if (empty($type)) {
             $type = C('DEFAULT_AJAX_RETURN');
         }
 
         switch (strtoupper($type)) {
             case 'JSON':
                 // 返回JSON数据格式到客户端 包含状态信息
                 header('Content-Type:application/json; charset=utf-8');
                 $data = json_encode($data, $json_option);
                 break;
             case 'JSONP':
                 // 返回JSON数据格式到客户端 包含状态信息
                 header('Content-Type:application/json; charset=utf-8');
                 $handler = isset($_GET[C('VAR_JSONP_HANDLER')]) ? $_GET[C('VAR_JSONP_HANDLER')] : C('DEFAULT_JSONP_HANDLER');
                 $data    = $handler . '(' . json_encode($data, $json_option) . ');';
                 break;
             case 'EVAL':
                 // 返回可执行的js脚本
                 header('Content-Type:text/html; charset=utf-8');
                 break;
         }
         exit($data);
     }


     public function rentIpTime() { 
        
          
        $tableName = 'AD_dns_ipRuleServer_api';    
        
        $postData = json_decode(file_get_contents('php://input'), true);  
        
        if (empty($postData['rent_time'])) {
            $this->ajaxReturn(['status' => 'error', 'message' => '租用时间不能为空!'], 'json');
            return;
        } 
        
        if (empty($postData['server_id'])) {
            $this->ajaxReturn(['status' => 'error', 'message' => '服务器ID不存在!'], 'json');
            return;
        } 
        
        $server_id = $postData['server_id'];
        $rent_time = $postData['rent_time']; 
    
        $rentTime = strtotime($rent_time);
        $where = []; 
        if (!empty($server_id)) {
            $where['server_id'] = $server_id;
        }  
          
        $result = ADdnsIpRuleServerApi::where($where)
            ->update([
                'rent_time' => $rentTime,
            ]); 
    
        if ($result) {
            $this->ajaxReturn(['status' => 'success', 'message' => '租用成功','time' => $rentTime], 'json');
        } else {
            $this->ajaxReturn(['status' => 'error', 'message' => '租用失败'], 'json');
        }  
    }

    public function deleteIpByGroup() { 
        
        $postData = json_decode(file_get_contents('php://input'), true); 
        
        if (empty($postData['server_id'])) {
            $this->ajaxReturn(['status' => 'error', 'message' => '该台服务器不存在!'], 'json');
            return;
        }
        $server_id = trim(str_replace('组','',$postData['server_id'])); 
        
        $where = [];
        if (!empty($server_id)) {
            $where['server_id'] = $server_id;
        } 
        
        $result = ADdnsIpRuleServerApi::where($where)->delete(); 
    
        if ($result) {
            $this->ajaxReturn(['status' => 'success', 'message' => '成功删除'.$result.'条。'], 'json');
        } else {
            $this->ajaxReturn(['status' => 'error', 'message' => '删除失败'], 'json');
        } 
    }

    public function deleteDialogIp() { 
        
        $postData = json_decode(file_get_contents('php://input'), true); 
        
        if (empty($postData['deleteInfo']['server_addr'])) {
            $this->ajaxReturn(['status' => 'error', 'message' => 'ip地址不能为空!'], 'json');
            return;
        } 
        $id = $postData['deleteInfo']['id'];
        $ip = $postData['deleteInfo']['server_addr'];
    
        $type = $postData['type'];
    
        $msg = '';
        if($type == 'notuse'){
            $result = ADdnsIpRuleServerApi::where(['id' => $id])->update(['status' => 1]);
            $msg = $ip. '禁用成功！';
        }elseif($type == 'use'){
            $result = ADdnsIpRuleServerApi::where(['id' => $id])->update(['status' => 0]);
            $msg = $ip. '启用成功！';
        }else {
            $result = ADdnsIpRuleServerApi::where(['id' => $id])->delete();
            $msg = $ip.'删除成功！';
        } 
    
        if ($result !== false) {
            $this->ajaxReturn(['status' => 'success', 'message' => $msg], 'json');
        } else {
            $this->ajaxReturn(['status' => 'error', 'message' => '操作失败！'], 'json');
        }  
    }

    public function updateIpDetails() { 
        
        $postData = json_decode(file_get_contents('php://input'), true);   
    
        if (empty($postData['updated_details']['server_addr'])) {
            $this->ajaxReturn(['status' => 'error', 'message' => 'ip地址不能为空!'], 'json');
            return;
        }
        if (empty($postData['updated_details']['server_id'])) {
            $this->ajaxReturn(['status' => 'error', 'message' => '服务器ID不能为空!'], 'json');
            return;
        }
        $ori_server_addr = $postData['server_addr'];
    
        $server_addr = trim($postData['updated_details']['server_addr']);
    
        $ipv4Pattern = '/^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/';
        $ipv6Pattern = '/^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/';
    
        if (!preg_match($ipv4Pattern, $server_addr) && !preg_match($ipv6Pattern, $server_addr)) {
            $this->ajaxReturn(['status' => 'error', 'message' => 'IP地址不符合规范!'], 'json');
        } 
    
        $id = $postData['updated_details']['id'];  
        $exist = ADdnsIpRuleServerApi::where("id <> $id AND server_addr = '$server_addr'")->find();
        if($exist){
            $this->ajaxReturn(['status' => 'error', 'message' => '数据库已存在该IP!'], 'json');
        } 
    
        $server_id = trim($postData['updated_details']['server_id']);  
    
        $is_main_addr = $postData['updated_details']['is_main_addr']; 
    
        if($is_main_addr){ 
            ADdnsIpRuleServerApi::where(['server_id' => $server_id])
                ->where(['is_main_addr' => $is_main_addr])
                ->update(['is_main_addr' => 0]);
        } 
    
        $status = $postData['updated_details']['status'];
    
        $updateData = [ 
            'server_id' => $server_id,
            'server_addr' => $server_addr,
            'is_main_addr' => $is_main_addr, 
            'status' => $status, 
            'update_time' => time()  
        ];  
    
        $result = ADdnsIpRuleServerApi::where(['id' => $id])->update($updateData);
    
        if ($result !== false) {
            $this->ajaxReturn(['status' => 'success', 'message' => 'IP 详情更新成功'], 'json');
        } else {
            $this->ajaxReturn(['status' => 'error', 'message' => '更新失败，请稍后重试'], 'json');
        } 
    }


  
public function exportDataToExcelOne($data)
{
    // 设置内存和执行时间限制
    ini_set('memory_limit', '512M');
    ini_set('max_execution_time', 300);

    // 创建一个新的 Spreadsheet 对象
    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    $sheet->setTitle('Exported Data'); // 设置表格标题

    // 设置初始行号
    $rowIndex = 1;
    $col = 'A';

    // 遍历数据并写入 Excel
    foreach ($data as $rule => $groups) {
        $sheet->getColumnDimension($col)->setWidth(50);
        $count = count($data[$rule]);

        // 获取起始列和结束列的字母表示
        $startColumn = $col; // 假设 $col 是起始列
        $endColumn = chr(ord($col) + $count - 1); // 计算结束列

        // 合并单元格
        $sheet->mergeCells("{$startColumn}{$rowIndex}:{$endColumn}{$rowIndex}");

        // 设置合并单元格的值
        $sheet->setCellValue($startColumn . $rowIndex, '服务器 IP 数据总览');

        // 创建一个样式数组
        $styleArray = [
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT, // 设置水平左对齐
            ],
        ];
        // 应用样式到单元格
        $sheet->getStyle($startColumn . $rowIndex)->applyFromArray($styleArray);

        $k = $rowIndex + 1;

        foreach ($groups as $group => $groupData) {
            // 写入组名和租用时间
            $i = $k;
            $sheet->setCellValue($col . $i, '服务器' . $group);
            $i++;

            $rentTime = '';
            if (!empty($groupData['time'])) {
                $rentTime = date('Y-m-d H:i:s', $groupData['time']);
            }
            $sheet->setCellValue($col . $i, '租用时间：' . $rentTime);
            $i++;

            // 合并并写入 IP 地址
            $ipStrings = [];
            foreach ($groupData['ips'] as $ipData) {
                $ip = $ipData['ip'];
                if ($ipData['is_main_addr'] === '2') {
                    $ip .= ' 主'; // 标记主 IP
                } elseif ($ipData['is_main_addr'] === '1') {
                    $ip .= ' 落地页'; // 标记主 IP
                }
                $sheet->setCellValue($col . $i, $ip);
                $i++;
            }
            $col++;
            $sheet->getColumnDimension($col)->setWidth(50);
        }
    }

    // 输出为新的 Excel 文件
    $filename = 'exported_data_' . date('YmdHis') . '.xlsx';
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="' . $filename . '"');
    header('Cache-Control: max-age=0');
    header('Cache-Control: max-age=1');
    $writer = new Xlsx($spreadsheet);
    $writer->save('php://output');
    exit;
}
 
 
     // 继续重写其他方法，使用模型类替换数据库操作
 }
 